﻿/*

The MIT License

Copyright (c) 2010 Cartesian Analytics, Inc. 

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

namespace Pipra.Math.Geometry
{
    /// <summary>
    /// A connected string of line segments.
    /// </summary>
    public class LineString2
        :
        Collection<Point2>,
        ICurve2<double>,
        IEquatable<LineString2>,
        IIntersectable<Point2>,
        IHasDistance<double,Point2>,
        IContainable<Mbr>,
        ICloneable
    {

        public static bool operator==(LineString2 a, LineString2 b)
        {
            return ReferenceEquals(a, b) || (!ReferenceEquals(null, a) && a.Equals(b));
        }

        public static bool operator!=(LineString2 a, LineString2 b)
        {
            return !ReferenceEquals(a, b) && (ReferenceEquals(null, a) || !a.Equals(b));
        }


        /// <summary>
        /// Constructs a new empty line string.
        /// </summary>
        public LineString2() { }
        /// <summary>
        /// Creates a new empty line string expecting the given number of points.
        /// </summary>
        /// <param name="expectedCapacity">The expected number of points.</param>
        public LineString2(int expectedCapacity)
            : base(new List<Point2>(expectedCapacity)) { }
        /// <summary>
        /// Constructs a new line string containing the given ordered set of points.
        /// </summary>
        /// <param name="points">The ordered set of points the line string will be composed of.</param>
        public LineString2(IEnumerable<Point2> points)
            : base(null == points ? new List<Point2>() : new List<Point2>(points)) { }

        /// <summary>
        /// The number of line segments the line string is composed of.
        /// </summary>
        public int SegmentCount
        {
            get
            {
                return System.Math.Max(0,Count - 1);
            }
        }
        /// <summary>
        /// Extracts a line segment from the line string at the given segment index <paramref name="i"/>.
        /// </summary>
        /// <param name="i">The segment index.</param>
        /// <returns>A line segment.</returns>
        public Segment2 GetSegment(int i)
        {
            int nexti = i + 1;
            if (i < 0 || (nexti >= Count))
            {
                throw new ArgumentOutOfRangeException("i", "'i' must be positive and less than the number of segments in this line string");
            }
            return new Segment2(this[i], this[nexti]);
        }

        /// <summary>
        /// The first point in the line string.
        /// </summary>
        public Point2 A
        {
            get
            {
                return Count < 1 ? Point2.Invalid : this[0];
            }
        }
        IPoint2<double> ICurve2<double>.A
        {
            get { return A; }
        }
        /// <summary>
        /// The last point in the line string.
        /// </summary>
        public Point2 B
        {
            get
            {
                return Count < 1 ? Point2.Invalid : this[Count-1];
            }
        }
        IPoint2<double> ICurve2<double>.B
        {
            get { return B; }
        }
        /// <summary>
        /// The overall direction of the line string.
        /// </summary>
        public Vector2 Direction
        {
            get
            {
                return Count < 2 ? Vector2.ZeroVector : this[Count - 1].Difference(this[0]);
            }
        }
        IVector2<double> ICurve2<double>.Direction
        {
            get { return Direction; }
        }
        /// <summary>
        /// Calculates the distance between this line string and the point, <paramref name="p"/>
        /// </summary>
        /// <param name="p">The point to calculate distance to.</param>
        /// <returns>The distance.</returns>
        public double Distance(Point2 p)
        {
            return System.Math.Sqrt(DistanceSquared(p));
        }
        /// <summary>
        /// Calculates the distance between this line string and the point, <paramref name="p"/>
        /// </summary>
        /// <param name="p">The point to calculate distance to.</param>
        /// <returns>The distance.</returns>
        public double Distance(IPoint2<double> p)
        {
            return Distance(new Point2(p));
        }
        /// <summary>
        /// Calculates the squared distance between this line string and the point, <paramref name="p"/>
        /// </summary>
        /// <param name="p">The point to calculate squared distance to.</param>
        /// <returns>The squared distance.</returns>
        public double DistanceSquared(Point2 p)
        {
            int lasti = Count - 1;
            if (1 <= lasti)
            {
                double d = Segment2.DistanceSquared(this[0], this[1], p);
                for (int i = 1, nexti = 2; i < lasti; i = nexti++)
                {
                    d =  System.Math.Min(d, Segment2.DistanceSquared(this[i], this[nexti], p));
                }
                return d;
            }
            return (0 == lasti) ? (this[0].DistanceSquared(p)) : Double.NaN;
        }
        /// <summary>
        /// Calculates the squared distance between this line string and the point, <paramref name="p"/>
        /// </summary>
        /// <param name="p">The point to calculate squared distance to.</param>
        /// <returns>The squared distance.</returns>
        public double DistanceSquared(IPoint2<double> p)
        {
            return DistanceSquared(new Point2(p));
        }
        /// <summary>
        /// Determines if a point intersects this line string.
        /// </summary>
        /// <param name="p">A point to test intersection with.</param>
        /// <returns>True when a point intersects this line string.</returns>
        public bool Intersects(Point2 p)
        {
            int lasti = Count - 1;
            if (lasti >= 1)
            {
                for (int i = 0, nexti = 1; i < lasti; i = nexti++)
                {
                    if (Segment2.Intersects(this[i], this[nexti], p))
                    {
                        return true;
                    }
                }
            }
            return lasti == 0 && this[0].Equals(p);
        }
        /// <summary>
        /// Determines if a point intersects this line string.
        /// </summary>
        /// <param name="p">A point to test intersection with.</param>
        /// <returns>True when a point intersects this line string.</returns>
        public bool Intersects(IPoint2<double> p)
        {
            return Intersects(new Point2(p));
        }
        /// <summary>
        /// Calculates a minimum bounding rectangle for this line string.
        /// </summary>
        /// <returns>A minimum bounding rectangle.</returns>
        public Mbr GetMbr()
        {
            if (Count > 1)
            {
                Mbr result = new Mbr(this[0], this[1]);
                for (int i = 2; i < Count; i++)
                {
                    result = result.Union(this[i]);
                }
                return result;
            }
            return (1 == Count) ? new Mbr(this[0]) : Mbr.Invalid;
        }
        IMbr<double> IHasMbr<double>.GetMbr()
        {
            return GetMbr();
        }
        /// <summary>
        /// Calculates the centroid.
        /// </summary>
        /// <returns>A centroid.</returns>
        public Point2 GetCentroid()
        {
            int lasti = Count - 1;
            if (lasti > 0)
            {
                double msum = 0;
                double xsum = 0;
                double ysum = 0;
                for (int i = 0, nexti = 1; i < lasti; i = nexti++)
                {
                    double m = this[i].DistanceSquared(this[nexti]);
                    msum = msum + m;
                    m = m / 2.0;
                    xsum = (xsum + ((this[i].X + this[nexti].X) * m));
                    ysum = (ysum + ((this[i].Y + this[nexti].Y) * m));
                }
                if (0 != msum)
                {
                    return new Point2(xsum / msum, ysum / msum);
                }
            }
            return (lasti == 0) ? this[0] : Point2.Invalid;
        }
        IPoint2<double> IHasPlanarCentroid<double>.GetCentroid()
        {
            return GetCentroid();
        }
        /// <summary>
        /// Calculates the magnitude of this line string.
        /// </summary>
        /// <returns>The magnitude.</returns>
        public double GetMagnitude()
        {
            int lasti = Count - 1;
            if (1 <= lasti)
            {
                double sum = this[0].Distance(this[1]);
                for (int i = 1, nexti = 2; i < lasti; i = nexti++)
                {
                    sum += this[i].Distance(this[nexti]);
                }
                return sum;
            }
            return 0;
        }
        /// <summary>
        /// Calculates the squared magnitude of this line string.
        /// </summary>
        /// <returns>The magnitude.</returns>
        public double GetMagnitudeSquared()
        {
            double m = GetMagnitude();
            return m * m;
        }
        /// <summary>
        /// Indicates whether the current object is equal to another object of the same type.
        /// </summary>
        /// <returns>
        /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
        /// </returns>
        /// <param name="other">An object to compare with this object.</param>
        public bool Equals(LineString2 other)
        {
            if (ReferenceEquals(this, other))
            {
                return true;
            }
            if (ReferenceEquals(null, other))
            {
                return false;
            }
            if (Count == other.Count)
            {
                for (int i = 0; i < Count; i++)
                {
                    if (!this[i].Equals(other[i]))
                    {
                        return false;
                    }
                }
                return true;
            }
            return false;
        }

        /// <summary>
        /// Serves as a hash function for a particular type. 
        /// </summary>
        /// <returns>
        /// A hash code for the current <see cref="T:System.Object"/>.
        /// </returns>
        /// <filterpriority>2</filterpriority>
        public override int GetHashCode()
        {
            return GetMbr().GetHashCode() ^ 1020930680;
        }

        /// <summary>
        /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
        /// </summary>
        /// <returns>
        /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false.
        /// </returns>
        /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param>
        /// <filterpriority>2</filterpriority>
        public override bool Equals(object obj)
        {
            return null != obj
                && (
                    (obj is LineString2 && Equals(obj as LineString2))
                )
            ;
        }

        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder(String.Concat("LineString, ", Count, "point"));
            if (1 != Count)
            {
                sb.Append('s');
            }
            if (Count < 4)
            {
                for (int i = 0; i < Count; i++)
                {
                    sb.Append(' ');
                    sb.Append(this[i].ToString());
                }
            }
            return sb.ToString();
        }
        /// <summary>
        /// Creates an identical line string.
        /// </summary>
        /// <returns>A line string.</returns>
        public LineString2 Clone()
        {
            return new LineString2(this);
        }
        object ICloneable.Clone()
        {
            return Clone();
        }
        /// <summary>
        /// Determines if the given MBR contains this line string.
        /// </summary>
        /// <param name="mbr">The MBR to test.</param>
        /// <returns>True if this instance is within the given MBR.</returns>
        public bool Within(Mbr mbr)
        {
            return GetMbr().Within(mbr);
        }
        /// <summary>
        /// Determines if the given MBR contains this line string.
        /// </summary>
        /// <param name="mbr">The MBR to test.</param>
        /// <returns>True if this instance is within the given MBR.</returns>
        public bool Within(IMbr<double> mbr)
        {
            return GetMbr().Within(mbr);
        }

        /// <summary>
        /// Determines if this line string is self-intersecting.
        /// </summary>
        /// <returns>True if self-intersecting.</returns>
        public bool IsSelfIntersecting()
        {
            throw new NotImplementedException();
        }
    }
}
